package com.itmuch.core.db;

import org.apache.ibatis.mapping.MappedStatement;

import com.github.miemiedev.mybatis.paginator.dialect.Dialect;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;

public class MySQLDialect extends Dialect {

    public MySQLDialect(MappedStatement mappedStatement, Object parameterObject, PageBounds pageBounds) {
        super(mappedStatement, parameterObject, pageBounds);
    }

    @Override
    protected String getLimitString(String sql, String offsetName, int offset, String limitName, int limit) {

        StringBuffer buffer = new StringBuffer(sql.length() + 20).append(sql);
        if (offset > 0) {
            buffer.append(" limit ?, ?");
            this.setPageParameter(offsetName, offset, Integer.class);
            this.setPageParameter(limitName, limit, Integer.class);
        } else {
            buffer.append(" limit ?");
            this.setPageParameter(limitName, limit, Integer.class);
        }
        return buffer.toString();
    }

    @Override
    protected String getCountString(String sql) {
        // 去除空行、转小写
        StringBuffer sqlSb = new StringBuffer(sql.toLowerCase().replaceAll("(\r\n|\r|\n|\n\r)", " "));

        if (sqlSb.indexOf("group by") > 0) {
            return "select count(1) from (" + sql + ") tmp_count";
        } else {
            int index = sqlSb.indexOf("from ");
            sqlSb.replace(0, index, "select count(1) \n");
        }
        return sqlSb.toString();
    }
}
